<!--  -->
<template>
    <div class="app-container">
        <div class="container">
            <el-row>
                <el-form :inline="true" :model="listQuery">
                    <el-form-item label="币种">
                        <el-input v-model="listQuery.token" placeholder="名称" clearable />
                    </el-form-item>
                    <!-- <el-form-item label="策略" style="width: 200px;">
                        <el-select v-model="listQuery.strategyName" placeholder="策略" clearable>
                            <el-option v-for="item in strategyList" :label="item.value" :key="item.key"
                                :value="item.key" />
                        </el-select>
                    </el-form-item> -->
                    <el-form-item>
                        <el-button type="primary" @click="onSearch">查询</el-button>
                        <el-button type="primary" @click="onCreate">创建</el-button>
                    </el-form-item>
                </el-form>
            </el-row>
            <el-row>
                <el-table :data="list" v-loading="listLoading" element-loading-text="拼命加载中" border fit
                    highlight-current-row>
                    <el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
                    <el-table-column prop="token" label="币种" width="145" align="center"></el-table-column>
                    <el-table-column label="时间周期" align="center">
                        <template #default="scope">
                            <el-tag v-if="scope.row.periodIntList" style="margin-left: 5px;" v-for="(item,index) in scope.row.periodIntList">{{ periodDesc[item] }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="strategyName" label="计算方法" width="145" align="center"></el-table-column>
                    <el-table-column prop="strategyCName" label="策略" width="145" align="center"></el-table-column>
                    <el-table-column prop="status" label="状态" width="145" align="center">
                        <template #default="scope">
                            <el-tag>{{ statusDesc[scope.row.status] || '正常'}}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" width="185">
                        <template #default="scope">
                            <!-- <el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button> -->
                            <el-button link type="primary" @click="handleSet(scope.row)">周期设置</el-button>
                            <el-button link type="primary" v-if="!scope.row.status"
                                @click="handleStatus(scope.row, 1)">启用</el-button>
                            <el-button link type="primary" v-else
                                @click="handleStatus(scope.row, 0)">禁用</el-button>
                            <!--<el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index, scope.row)" >删除</el-button>-->
                        </template>
                    </el-table-column>
                </el-table>
                <!-- 分页 -->
                <div class="pagination">
                    <el-pagination layout="sizes, total, prev, pager, next" :page-sizes="[10, 20, 30]"
                        v-model:page-size="listQuery.rows" v-model:currentPage="listQuery.page" @current-change="(val) => {
                            fetchData();
                        }
                            " @size-change="(val) => {
                                fetchData();
                            }
                                " :total="totalRecord"></el-pagination>
                </div>
            </el-row>
        </div>
        <!-- 新增弹出框 -->
        <el-dialog :title="isAdd ? '新增' : '编辑'" v-model="addFormVisible" :close-on-click-modal="false" width="600px">
            <el-form ref="form" :model="form" label-width="60px">
                <el-input v-model="form.id" type="hidden"></el-input>
                <el-form-item label="币种" :label-width="formLabelWidth">
                    <el-input v-model="form.token" style="width: 300px"></el-input>
                </el-form-item>

                <el-form-item label="周期" :label-width="formLabelWidth">
                    <el-checkbox-group v-model="checkList">
                        <el-checkbox v-for="item in columns" :key="item.value" :label="String(item.value)">{{  item.text }}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="onSave" :loading="formLoading">保 存</el-button>
                </span>
            </template>
        </el-dialog>

        <el-dialog title="策略周期全局设置" v-model="dialogVisiable" :close-on-click-modal="false" width="600px">
            <el-form ref="form"  label-width="120px">
                <el-checkbox-group v-model="checkList">
                    <el-checkbox v-for="item in columns" :key="item.value" :label="String(item.value)">{{  item.text }}</el-checkbox>
                </el-checkbox-group>
            </el-form>
            <template #footer>
                <span class="dialog-footer">

                    <el-button @click="dialogVisiable = false">取 消</el-button>
                    <el-button type="primary" @click="handleReset()" :loading="formLoading">重置</el-button>
                    <el-button type="primary" @click="onSubmitPointsChange()" :loading="formLoading">提交</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { query, save, iconUpdata, getStrategy, saveStatus } from '@/api/icon';
import { utilsMixin } from '@/mixin/utils';
export default {
    name: 'IconConfig',
    mixins: [utilsMixin],
    data() {
        return {
            dialogVisiable: false,
            currentStrategy: {},
            checkList: [],
            strategyList: [],
            periodDesc: {
                1: '5分钟',
                2: '15分钟',
                3: '30分钟',
                4: '1小时',
                7: '2小时',
                5: '4小时',
                8: '6小时',
                9: '12小时',
                6: '日线',
            },
            columns: [
                { text: '5分钟', value: '1', select: false },
                { text: '15分钟', value: '2', select: false },
                { text: '30分钟', value: '3', select: false },
                { text: '1小时', value: '4', select: false },
                { text: '2小时', value: '7', select: false },
                { text: '4小时', value: '5', select: false },
                { text: '6小时', value: '8', select: false },
                { text: '12小时', value: '9', select: false },
                { text: '日线', value: '6', select: false },
            ],
            list: [], // 列表数据
            listLoading: true, // 加载状态
            totalRecord: 0, // 数据总条数
            listQuery: {
                page: 1,
                pageSize: 10,
                token: '',
                strategyName: '',
            },
            listQueryParam: { page: 1 },
            formLabelWidth: '160px',
            formLoading: false,
            addFormVisible: false, // 新增单窗
            isAdd: false, // 当前是否是新增
            form: {
                id: '',
                token: '',
                strategy: 'COPYCAT',
                periods: '6'
            },
            statusDesc: {
                0: '正常',
                99: '禁用',
            },
        };
    },
    created() {
        this.fetchData();
    },
    methods: {
        fetchData() {
            this.listLoading = true;
            query(this.listQuery).then((response) => {
                if (response.success && response.data != null) {


                    this.list = response.data.records;
                    this.totalRecord = response.data.total;
                }
                this.listLoading = false;
            })
            .catch(() => {
                this.listLoading = false;
            });
            getStrategy().then(res => {
                if (res.code === 20000) {
                    this.strategyList = res.data;
                }
            })
            const strategyListData = {
                "COPYCAT": "山寨策略",
                "EMASMA": "异动策略",
                "SUPERTREND": "波段策略(12H为中长线策略)",
                "EMA": "高低点分型策略",
                "DEMA": "AG趋势策略"
            };
            this.strategyList = Object.keys(strategyListData).map(item => ({
                key: item,
                value: strategyListData[item]
            }));
            console.log('===', this.strategyList)
            this.totalRecord = 30;
        },

        handleSet(row) {
            this.currentStrategy = row;
            this.checkList = row.periodIntList.map(item => String(item));
            console.log('=======', this.checkList)
            this.dialogVisiable = true;
        },
        handleReset() {
            let checkList = [];
            switch (this.currentStrategy.id) {
                case 1:
                    checkList = ['5']; // 默认4h
                    break;
                case 2:
                    checkList = ['3', '4', '7', '5', '9', '6']; // 默认30分钟，1h，2h，4h，12h，日线
                    break;
                case 3:
                    checkList = ['7', '5', '8']; // 2h，4h，6h
                    break;
                case 4:
                    checkList = ['5']; // 默认1h
                    break;
                case 5:
                    checkList = ['9', '6'];  // 默认12h,日线
                    break;
            
                default:
                    break;
            }
            this.checkList = checkList;
        },
        handleStatus(row, type) {
            saveStatus(row.id).then(res => {
                if (res.code === 20000) {
                    this.$message({
                        message: `${type === 1 ? '启用' : '禁用'}成功！`,
                        type: 'success',
                    });
                    this.fetchData();
                }
            })
        },
        onSubmitPointsChange() {
            console.log(this.checkList);
            this.formLoading = true
            
            let periodArr = [];
            this.columns.forEach(item => {
                if (this.checkList.includes(item.value)) {
                    periodArr.push(item.value)
                }
            })
            iconUpdata({
                id: this.currentStrategy.id,
                periods: this.checkList.join(',')
            }).then(() => {
                this.formLoading = false
                this.dialogVisiable = false
                this.fetchData()
            }).catch(() => {
                this.formLoading = false
            })
        },
        // 查询
        onSearch() {
            this.listQuery = Object.assign(this.listQuery, this.listQueryParam); // 合并对象
            this.fetchData();
        },
        clearForm() {
            this.form = {
                id: '',
                value: '',
                name: '',
                title: '',
                status: 0,
            };
        },
        onCreate() {
            this.clearForm();
            this.addFormVisible = true;
            this.isAdd = true;
        },
        // 编辑
        handleEdit(row) {
            this.form = Object.assign(this.form, row); // 合并对象
            this.addFormVisible = true;
            this.isAdd = false;
        },
        onSave() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.formLoading = true;
                    save({
                        strategy: 'COPYCAT',
                        token: this.form.token,
                        periods: 6,
                    }).then((response) => {
                        this.formLoading = false;
                        if (response.success) {
                            this.$message({
                                message: '保存成功！',
                                type: 'success',
                            });
                            this.addFormVisible = false;
                            this.fetchData();
                        } else {
                            this.$message({
                                message: '保存失败：' + response.msg,
                                type: 'error',
                            });
                        }
                    })
                    .catch(() => {
                        this.formLoading = false;
                    }); // end of createOrUpdate
                }
            }); // end of validate
        },
    },
};
</script>
